//
//  AppDelegate+OCRunner.m
//  OCRunner_Use
//
//  Created by 1084-Wangcl-Mac on 2022/9/2.
//  Copyright © 2022 Charles2021. All rights reserved.
//

#import "AppDelegate+OCRunner.h"
#import "ORInterpreter.h"
#import <AFNetworking.h>
#import <SSZipArchive.h>
#import "ORSystemFunctionPointerTable.h"
#import "NSData+YCTool.h"

@implementation AppDelegate (OCRunner)

- (void)loadOCRunner {
#if 0
    NSString *finalPath = [[NSBundle mainBundle] pathForResource:@"binarypatch" ofType:nil];
    [ORInterpreter excuteBinaryPatchFile:finalPath];
#else
    
    //若补丁已经下载好并解压了，就读取本地的补丁，避免每次都去下载新的补丁
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSString *finalPath = [[documentsDirectoryURL.absoluteString stringByAppendingPathComponent:@"binarypatch_Test/binarypatch"] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
    NSString *patchInfoPath = [[documentsDirectoryURL.absoluteString stringByAppendingPathComponent:@"binarypatch_Test/binarypatchVersion.txt"] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
    
    //获取版本信息,进行版本对比,若大于本地版本,则进行更新下载,否则,进行加载本地下载好的patch文件
    // 本地存储版本
    __block int patchVersion;
    // 服务器版本
    __block int patchServerVerion;
    [self getClientConfigDatas:^(BOOL success, int version) {
        if(success) {
            NSLog(@"%ld",(long)version);
            patchServerVerion = version;
            
            // 本地版本为-1,服务器版本 > 本地版本 (本地已下载的前提下),否则直接请求网络
            if([NSFileManager.defaultManager fileExistsAtPath:patchInfoPath]) {
                patchVersion = [self getLocalPatchVersion:patchInfoPath];
                if(patchVersion == -1 || patchServerVerion > patchVersion) {
                    [self downloadPatchFromnet];
                } else {
                    [self loadFromSandbox];
                }
            } else {
                [self downloadPatchFromnet];
            }
        } else {
            [self loadFromSandbox];
        }
    }];
#endif
}

// 获取本地版本
-(int)getLocalPatchVersion:(NSString *)filePath {
    //本地版本
    
    //服务器 > 本地----更新
    // 读取文件并解析为字典
    if([NSFileManager.defaultManager fileExistsAtPath:filePath]) {
        NSDictionary *result = readTxtFileAndParseToDictionary(filePath);
        if (result) {
            NSLog(@"解析后的字典: %@", result);
            
            return [[[NSString stringWithFormat:@"%@",[result valueForKey:@"patchVersion"]] stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
        }
    }
    return -1;
}

// 获取服务器补丁版本号
- (void)getClientConfigDatas:(void (^)(BOOL success, int version))completion {
    NSString *reqUrlStr = @"https://test-gateway.devproxy.yicheapp.vip/files/download/yryc-test/yiche-uniapp/Test/OCrunner/binarypatchVersion.txt";
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:reqUrlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [data dataToJson];
        int version = [[[dict valueForKey:@"patchVersion"] stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion)
            {
                if (error) {
                    completion(NO, -1);
                    return;
                }
                
                if (dict)
                {
                    completion(YES, version);
                }
                else
                {
                    completion(NO, -1);
                }
            }
        });
    }];
    [task resume];
}

// 删除本地文件
- (void)deleteLocalPatch:(void (^)(BOOL success))completion {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSString *finalPath = [[documentsDirectoryURL.absoluteString stringByAppendingPathComponent:@"binarypatch_Test"] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
    NSError* error = nil;
    BOOL isDelete = false;
    if([NSFileManager.defaultManager fileExistsAtPath:finalPath]) {
        isDelete = [NSFileManager.defaultManager removeItemAtPath:finalPath error:&error];
        if (isDelete) {
            completion(YES);
        } else {
            completion(NO);
        }
    } else {
        completion(NO);
    }
}
//本地加载补丁
- (void)loadFromSandbox {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSString *finalPath = [[documentsDirectoryURL.absoluteString stringByAppendingPathComponent:@"binarypatch_Test/binarypatch"] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
    if ([NSFileManager.defaultManager fileExistsAtPath:finalPath]) {
        [ORInterpreter excuteBinaryPatchFile:finalPath];
    }
}

// 下载补丁到本地
- (void)downloadPatchFromnet {
    
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    //创建信号量，保证先把补丁包下载下来再进入主页面，若补丁包大的话，可以考虑不阻塞主线程，给予等待loading显示
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    NSURL *URL = [NSURL URLWithString:@"https://test-gateway.devproxy.yicheapp.vip/files/download/yryc-test/yiche-uniapp/Test/OCrunner/binarypatch_Test.zip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error == nil) {
            NSString *filePathStr = filePath.relativePath;
            NSString *toPath = [filePathStr stringByDeletingLastPathComponent];
            NSString *finalPath = [NSString stringWithFormat:@"%@/binarypatch_Test/binarypatch", toPath];
            //先移除已存在的解压包，以防解压过后的文件干扰到，取不到最新的二进制文件
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:finalPath]) {
                [fileManager removeItemAtPath:finalPath error:nil];
            }
            [SSZipArchive unzipFileAtPath:filePathStr toDestination:toPath progressHandler:nil completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
                NSLog(@"解压缩地址 \n%@", finalPath);
                [ORInterpreter excuteBinaryPatchFile:finalPath];
                
                if([NSFileManager.defaultManager fileExistsAtPath:filePathStr]) {
                    [NSFileManager.defaultManager removeItemAtPath:filePathStr error:&error];
                }
                
                //存储版本号到本地
                NSString *patchInfoPath = [[documentsDirectoryURL.absoluteString stringByAppendingPathComponent:@"binarypatch_Test/binarypatchVersion.txt"] stringByReplacingOccurrencesOfString:@"file:" withString:@""];
                NSDictionary *result = readTxtFileAndParseToDictionary(patchInfoPath);
                if (result) {
                    NSLog(@"解析后的字典: %@", result);
                }
                dispatch_semaphore_signal(semaphore);
            }];
        } else {
            dispatch_semaphore_signal(semaphore);
        }
    }];
    [downloadTask resume];
    
    //信号量等待
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}


// 读取本地 txt 文件并将内容解析为字典的函数
NSDictionary *readTxtFileAndParseToDictionary(NSString *filePath) {
    // 检查文件是否存在
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSLog(@"文件不存在: %@", filePath);
        return nil;
    }
    
    // 读取文件内容到字符串
    NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (!fileContent) {
        NSLog(@"读取文件失败: %@", filePath);
        return nil;
    }
    
    // 将字符串转换为 NSData
    NSData *jsonData = [fileContent dataUsingEncoding:NSUTF8StringEncoding];
    if (!jsonData) {
        NSLog(@"无法将字符串转换为 NSData");
        return nil;
    }
    
    // 解析 JSON 数据为字典
    NSError *error;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    if (error) {
        NSLog(@"解析 JSON 数据失败: %@", error.localizedDescription);
        return nil;
    }
    
    return resultDictionary;
}

@end
